//
//  JCClubInfoVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/20.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCClubInfoVC.h"
#import "JCClubInfoPlanWeekCell.h"
#import "JCClubInfoMessageCell.h"
#import "JCClubApi.h"
#import "JCClubModel.h"
#import "JCMessageListModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <UICountingLabel/UICountingLabel.h>
#import "JCClubMemberVC.h"
#import "JCClubInfoSectionHeader.h"
#import "JCClubApi.h"
#import "JCClubMessageVC.h"
#import "JCClubSetupVC.h"
#import "YFLoginHelper.h"
#import "YFAlertHelper.h"
#import "JCClubPasswordInputView.h"
#import "SQActionSheetView.h"

#define kBackImageViewHEIGHT 216.0

@interface JCClubInfoVC ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, JCClubInfoPlanWeekCellDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *backImageView;
@property (assign, nonatomic) CGSize headerImageBackSize;
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;

@property (weak, nonatomic) IBOutlet UILabel *clubNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UILabel *clubDescribeLabel;

@property (weak, nonatomic) IBOutlet UICountingLabel *pLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *hLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *plcLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBottom;
@property (strong, nonatomic) NSArray <JCClubMessageModel *> *messageList;
@property (strong, nonatomic) JCClubModel *clubModel;

@property (weak, nonatomic) IBOutlet UIButton *placeSendButton;
@property (weak, nonatomic) IBOutlet UITextField *messageInput;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *messageBoardBottom;
@property (weak, nonatomic) IBOutlet UIView *footerView;
@property (weak, nonatomic) IBOutlet UIView *messageBoard;

@property (strong, nonatomic) NSArray <NSString *> *leftTitles;
@property (assign, nonatomic) NSInteger scorllIndex;

@end

@implementation JCClubInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)loadData{
    __weak typeof(self)weakSelf = self;
    [JCClubApi getClubInfoWithClubID:_clubID complete:^(NSError *error, JCClubModel *clubInfo) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            weakSelf.clubModel = clubInfo;
            [weakSelf.backImageView sd_setImageWithURL:clubInfo.banner placeholderImage:kPlaceholdImage];
            [weakSelf.headerImageView sd_setImageWithURL:clubInfo.headIcon placeholderImage:kPlaceholdImage];
            weakSelf.clubNameLabel.text = [NSString stringWithFormat:@"%@(ID:%06ld)",clubInfo.name,clubInfo.clubID.integerValue];
            weakSelf.addressLabel.text = clubInfo.address;
            weakSelf.clubDescribeLabel.text = clubInfo.describe;
            weakSelf.navigationItem.title = clubInfo.name;
            [weakSelf.pLabel countFrom:0 to:clubInfo.memberCount.integerValue];
            [weakSelf.hLabel countFrom:0 to:clubInfo.duration.integerValue];
            [weakSelf.plcLabel countFrom:0 to:clubInfo.rankNumber.integerValue];
            
            weakSelf.messageList = clubInfo.messageList;
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)initCode{
    _headerImageBackSize = CGSizeMake(kYFScreenWidth, 216);
    _headerImageView.layer.cornerRadius = 3;
    _headerImageView.layer.masksToBounds = YES;
    _backImageView.layer.anchorPoint = CGPointMake(0.5, 1);
    
    _pLabel.format = @"%ld";
    _hLabel.format = @"%ld";
    _plcLabel.format = @"%ld";
    
    [_tableView registerClass:[JCClubInfoSectionHeader class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([JCClubInfoSectionHeader class])];
    
    _placeSendButton.layer.cornerRadius =
    _sendButton.layer.cornerRadius = 3;
    _placeSendButton.layer.masksToBounds =
    _sendButton.layer.masksToBounds = YES;
    
    [_tableView beginUpdates];
    if (_watchType == WatchClubTypeMyMemberGeneral ||
        _watchType == WatchClubTypeMyMemberAdmin) {
        _messageBoard.hidden = NO;
        _tableViewBottom.constant = 0;
        CGRect frame = _footerView.frame;
        frame.size.height = 53;
        _footerView.frame = frame;
        _footerView.hidden = NO;
        _leftTitles = @[@"Training Details Last Week",@"Plan For The Week",@"Schedule Of The Week"];
    }else{
        _messageBoard.hidden = YES;
        _tableViewBottom.constant = 0;
        CGRect frame = _footerView.frame;
        frame.size.height = 0;
        _footerView.frame = frame;
        _footerView.hidden = YES;
        _leftTitles = @[@"Plan For The Week"];
    }
    [_tableView endUpdates];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"club_menu_list"] style:UIBarButtonItemStyleDone target:self action:@selector(menuAction:)];
}

- (void)menuAction:(UIBarButtonItem *)sender{
    __weak typeof(self)weakSelf = self;
    SQActionSheetView *sheetView = [[SQActionSheetView alloc] initWithTitle:nil buttons:@[@"Report",@"Cancel"] colors:@[[UIColor blackColor],[UIColor blackColor]] buttonClick:^(SQActionSheetView *sheetView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [weakSelf reportAction:_clubID spotterIDType:SpotterIDTypeClub];
        }
    }];
    [sheetView showView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _clubModel?1:0;
    }else{
        return _messageList.count == 0 ? 1:_messageList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        JCClubInfoPlanWeekCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JCClubInfoPlanWeekCell class]) forIndexPath:indexPath];
        cell.watchType = _watchType;
        cell.delegate = self;
        NSArray *sportItems;
        if (_watchType == WatchClubTypeApplyForAmission) {
            
            sportItems = @[_clubModel.clubWeekTarget];
        }else if (_watchType == WatchClubTypeMyMemberGeneral ||
                  _watchType == WatchClubTypeMyMemberAdmin){
            
            sportItems = @[_clubModel.lastWeekActiveTarget, _clubModel.clubWeekTarget, _clubModel.curWeekActiveTarget];
        }else if (_watchType == WatchClubTypeOtherMember){
            
            sportItems = @[_clubModel.clubWeekTarget];
        }
        cell.sportItems = sportItems;
        return cell;
    }else{
        if (_messageList.count == 0) {
            return [tableView dequeueReusableCellWithIdentifier:@"JCClubInfoNoMessageCell" forIndexPath:indexPath];
        }else{
            JCClubInfoMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JCClubInfoMessageCell" forIndexPath:indexPath];
            [cell setMessageModel:_messageList[indexPath.row]];
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 380;
    }else{
        if (_messageList.count == 0) {
            return 170;
        }else{
            return 140;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kSectionHeaderHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    __weak typeof(self)weakSelf = self;
    JCClubInfoSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"JCClubInfoSectionHeader"];
    header.rightButtonAction = ^(SectionButtonType type){
        if (type == SectionButtonTypeSetup) {
            
            [weakSelf setupAction];
        }else if(type == SectionButtonTypeViewAll) {
            
            [weakSelf viewAllMessage];
        }else if(type == SectionButtonTypeRank) {
            
        }
    };
 
    NSString *leftTitle;
    if (section == 0) {
        if (_leftTitles.count == 1) {
            leftTitle = @"Plan For The Week";
        }else{
            leftTitle = _leftTitles[_scorllIndex];
        }
    }else{
        leftTitle = @"Message Board";
    }
    [header setleftTitle:leftTitle];
    
    if (_watchType == WatchClubTypeMyMemberAdmin && section == 0) {
        [header setRightTitle:@"Set Up"];
        header.buttonType = SectionButtonTypeSetup;
    }else if ((_watchType == WatchClubTypeMyMemberAdmin || _watchType == WatchClubTypeMyMemberGeneral)
              && section == 1) {
        [header setRightTitle:@"View All"];
        header.buttonType = SectionButtonTypeViewAll;
    }else{
        [header setRightTitle:@""];
    }
    
    return header;
}

- (void)scrollToIndex:(NSInteger)index{
    _scorllIndex = index;
    JCClubInfoSectionHeader *header = (JCClubInfoSectionHeader *)[_tableView headerViewForSection:0];
    [header setleftTitle:_leftTitles[index]];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        if (scrollView.contentOffset.y < 0) {
            CGFloat scala = (kBackImageViewHEIGHT - offsetY) / kBackImageViewHEIGHT;
            self.backImageView.transform = CGAffineTransformMakeScale(scala, scala);
        }
    }
    
    if (scrollView == _tableView) {

        CGFloat sectionHeaderHeight;
        sectionHeaderHeight = kSectionHeaderHeight;
        if (scrollView == _tableView) {
            if (scrollView.contentOffset.y<=sectionHeaderHeight && scrollView.contentOffset.y>=0) {
                scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
                scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
            }
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView.contentOffset.y < -100) {
        [self loadData];
    }
}

- (void)viewAllMessage{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ClubsExtension" bundle:[NSBundle mainBundle]];
    JCClubMessageVC *messageVC = [sb instantiateViewControllerWithIdentifier:@"JCClubMessageVC"];
    messageVC.clubID = _clubID;
    messageVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:messageVC animated:YES];
}

- (void)setupAction{
    __weak typeof(self)weakSelf = self;
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ClubsExtension" bundle:[NSBundle mainBundle]];
    JCClubSetupVC *setupVC = [sb instantiateViewControllerWithIdentifier:@"JCClubSetupVC"];
    setupVC.clubID = _clubID;
    setupVC.defaultValueItem = _clubModel.clubWeekTarget;
    setupVC.dismissHandle = ^{
        [weakSelf.tableView reloadData];
    };
    setupVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:setupVC animated:YES];
}

- (void)buttonActionType:(WatchClubType)type{
    
    __weak typeof(self)weakSelf = self;
    if (_watchType == WatchClubTypeApplyForAmission) {
        
        JCClubPasswordInputView *alertView = [[UINib nibWithNibName:@"JCClubPasswordInputView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
        alertView.number = _clubModel.clubPhone;
        PopupViewController *popVC = [YFAlertHelper showPresentInView:nil alertView:alertView withAlertViewFrame:CGRectMake(0, 0, 280, 227) animationType:DetailViewControllerPresentAnimationTypeDown tapMaskViewDismiss:YES];
        __weak typeof(popVC)weakPopVC = popVC;
        alertView.dismissHandle = ^(NSString *password){
            [weakPopVC dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
            if (password.length == 5) {
                [weakSelf.hud showWithMaskType:WSProgressHUDMaskTypeClear];
                [JCClubApi joinClubWithClubID:weakSelf.clubID password:password complete:^(NSError *error) {
                    if (error) {
                        [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                    }else{
                        [weakSelf.hud showSuccessWithStatus:@"Join Success" dimissAfterSecond:2];
                        [YFUserDefaults saveClubMeRefreshState:YES];
                    }
                }];
            }
        };
    }else{
        
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ClubsExtension" bundle:[NSBundle mainBundle]];
        JCClubMemberVC *memberVC = [sb instantiateViewControllerWithIdentifier:@"JCClubMemberVC"];
        memberVC.watchClubType = _watchType;
        memberVC.clubID = _clubID;
        memberVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:memberVC animated:YES];
    }
}

- (IBAction)editMessageAction:(UIButton *)sender {
    [_messageInput becomeFirstResponder];
    _messageBoard.alpha = 1;
}

- (IBAction)sendAction:(UIButton *)sender {
    if (_messageInput.text.length > 0) {
        __weak typeof(self)weakSelf = self;
        [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        [JCClubApi sendClubMessageWithClubID:_clubID content:_messageInput.text complete:^(NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                [weakSelf.hud dismiss];
                [weakSelf loadData];
            }
        }];
    }else{
        [self.hud showErrorWithString:@"Message Is Nil" dimissAfterSecond:2];
    }
    [_messageInput resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)notification{

    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height - (kDevice_Is_iPhoneX?35:0);
    _messageBoardBottom.constant = height;
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    _messageBoardBottom.constant = 0;
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
        _messageInput.text = @"";
        _messageBoard.alpha = 0;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
